package com.app.bimo.module_bookrack.mvp.ui.activity;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.launcher.ARouter;
import com.app.bimo.commonbusiness.base.BaseActivity;
import com.app.bimo.commonbusiness.util.Constant;
import com.app.bimo.commonbusiness.util.DataUtil;
import com.app.bimo.commonbusiness.util.HideUtil;
import com.app.bimo.commonbusiness.util.LoginService;
import com.app.bimo.commonbusiness.util.RouterHub;
import com.app.bimo.commonbusiness.util.SystemUtil;
import com.app.bimo.commonbusiness.view.AutoLineFeedView;
import com.app.bimo.commonbusiness.view.recyclerview.HeadFootRecyclerView;
import com.app.bimo.library_db.ADConfigData;
import com.app.bimo.library_db.SearchData;
import com.app.bimo.library_db.SearchHistory;
import com.app.bimo.library_db.UserData;
import com.app.bimo.library_db.helper.AdHelper;
import com.app.bimo.library_db.helper.SearchHistoryHelper;
import com.app.bimo.library_db.helper.UserHelper;
import com.app.bimo.module_bookrack.R;
import com.app.bimo.module_bookrack.mvp.constract.BookrackContract;
import com.app.bimo.module_bookrack.mvp.constract.BookrackSearchContract;
import com.app.bimo.module_bookrack.mvp.model.model.BookrackSearchModel;
import com.app.bimo.module_bookrack.mvp.persenter.BookrackSearchPresenter;
import com.app.bimo.module_bookrack.mvp.ui.adapter.BookrackSearchBookAdapter;
import com.bytedance.sdk.openadsdk.TTAdManager;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTNativeExpressAd;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.SimpleMultiPurposeListener;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.GridLayoutManager;
import butterknife.BindView;

import static com.app.bimo.commonbusiness.base.BaseApplication.getContext;

public class BookrackSearchActivity extends BaseActivity<BookrackSearchPresenter> implements View.OnClickListener, BookrackSearchContract.View, AutoLineFeedView.OnTagClickListener {


    private EditText searchEdit;
    private TextView right;
    private ImageView editCleanBtn;
    private GridLayout hotLay;
    private AutoLineFeedView feedLayout;   //
    private View searchNomal;
    private HeadFootRecyclerView listView;
    private BookrackSearchBookAdapter adapter;
    private View empty;
    private FrameLayout bannerLay;
    private Button mCreativeButton;
    private TextView searchHistoryTitle;

    private List<SearchData> searchList = new ArrayList<>();
    private List<AutoLineFeedView.AutoTextData> tags = new ArrayList<AutoLineFeedView.AutoTextData>();
    private List<SearchData> hotList = new ArrayList<>();     //搜索结果
    private List<SearchHistory> searchHistorys;               //搜索历史
    private Bundle bundle = new Bundle();



    private String searchKey;

    TTAdManager adManager;
    TTAdNative ttAdNative;
    private TTNativeExpressAd mTTAd;
    /**
     * 刷新
     */
    private SmartRefreshLayout refresh;
    private int page = 1;

    @Autowired(name = Constant.SearchKey)
    String bundleSearchKey;

    private UserData userData;
    private int interval = 2;


    @Override
    protected void initView() {

        searchNomal = findViewById(R.id.nomal);
        bannerLay = findViewById(R.id.bannerLay);
        hotLay = findViewById(R.id.hotGrid);
        searchHistoryTitle = findViewById(R.id.searchHistoryTitle);

        HideUtil.init(this);
        mPresenter = new BookrackSearchPresenter(new BookrackSearchModel(), this);
        userData = UserHelper.getsInstance().findUser();
        initToolbar();
        initFeedView();
        initHistoryData();
        initSearchResult();
        initRefresh();
        if (!DataUtil.isEmpty(bundleSearchKey)) {
            searchEdit.setHint(bundleSearchKey);
        }
        initEmpty();
//        initAdConfig();

    }

    @Override
    protected void initData() {
        mPresenter.requestHotSearchFromModel(false);
    }

    @Override
    protected void initEvent() {

    }

    @Override
    protected int setLayoutID() {
        return R.layout.bookeack_fragment_search_home;
    }

    @Override
    public void hotSearchNotify(List<SearchData> lists) {
        initHotData(lists);
        initHistoryData();
    }

    /**
     * 设置热搜
     * @param lists
     */
    private void initHotData(List<SearchData> lists) {
        hotList.clear();
        hotList.addAll(lists);
        if (hotList != null && hotList.size() > 0) {
            hotLay.removeAllViews();
            for (int i = 0; i < hotList.size(); i++) {
                View view = View.inflate(getContext(), R.layout.bookrack_view_search_history, null);
                view.setLayoutParams(new LinearLayout.LayoutParams(SystemUtil.getWidth(getContext()) / 2, ViewGroup.LayoutParams.WRAP_CONTENT));
                TextView num = view.findViewById(R.id.num);
                TextView bookName = view.findViewById(R.id.bookName);
                num.setText((i + 1) + "");
                if (i == 0) {
                    num.setTextColor(getResources().getColor(R.color.rF33604));
                } else if (i == 1) {
                    num.setTextColor(getResources().getColor(R.color.rFF521D));
                } else if (i == 2) {
                    num.setTextColor(getResources().getColor(R.color.rFF7611));
                } else {
                    num.setTextColor(getResources().getColor(R.color.g838A96));
                }
                bookName.setText(hotList.get(i).getNovelName());
                int finalI = i;
                view.setOnClickListener(v -> {
//                    bundle.putSerializable(Constant.BundleNovelid, hotList.get(finalI).getNovelid());
//                    bundle.putSerializable(Constant.BundleIsSearch, "1");
//                    ARUtil.navigationFragment(RouterHub.READ_BOOKDETAIL, getView(), bundle);
                });
                hotLay.addView(view);
            }

        } else {
            hotLay.removeAllViews();
            hotLay.setVisibility(View.GONE);
        }

    }


    @Override
    public void historyNotify(List<SearchHistory> lists) {

    }

    /**
     * 搜索结果回调
     * @param lists
     */
    @Override
    public void searchNotify(List<SearchData> lists) {
        refresh.finishLoadMore();
        refresh.finishRefresh();
        setlp(true);
        //隐藏默认UI
        searchNomal.setVisibility(View.GONE);
        if (page == 1) {
            searchList.clear();
        }
        searchList.addAll(lists);

        adapter.setSearchKey(searchKey);
        adapter.notifyDataSetChanged();
//        if (!((LoginService) ARouter.getInstance().build(RouterHub.ACCOUNT_SERVICE).navigation()).isVip()) {
//            ADConfigData data = AdHelper.getsInstance().getAdSearchResult();
//            if (data != null) {
//                if (data.getStatus().equals("1")) {
//                    loadListAd(data.getAdid());
//                }
//            }
//        }
        if (searchList.size() > 0) {
            empty.setVisibility(View.GONE);
        } else {
            empty.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void showSearchEmtyView() {

    }

    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.right) {
            search();
        }

        if (i == R.id.back) {
            finish();
        }
        if (i == R.id.editCleanBtn) {
            searchEdit.setText("");
        }
    }


    private void initToolbar() {
        mtoolbar = findViewById(R.id.toolbar);
        mtoolbar.setNavigationIcon(null);
        searchEdit = findViewById(R.id.searchEd);
        editCleanBtn = findViewById(R.id.editCleanBtn);
        editCleanBtn.setOnClickListener(this);
        findViewById(R.id.back).setOnClickListener(this);
        right = findViewById(R.id.right);
        right.setOnClickListener(this);
        editCleanBtn.setVisibility(View.GONE);
        searchEdit.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                search();
            }
            return true;
        });

        searchEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
//                if (delayRun != null) {
//                    //每次editText有变化的时候，则移除上次发出的延迟线程
//                    handler.removeCallbacks(delayRun);
//                }
                searchKey = s.toString();
                if (DataUtil.isEmpty(s.toString())) {
                    if (empty.getVisibility() == View.VISIBLE) {
                        empty.setVisibility(View.GONE);
                    }
                    if (searchNomal.getVisibility() == View.GONE) {
                        searchNomal.setVisibility(View.VISIBLE);
                        setlp(false);
                    }
                    editCleanBtn.setVisibility(View.GONE);
                } else {
                    //延迟800ms，如果不再输入字符，则执行该线程的run方法
//                    handler.postDelayed(delayRun, 800);
                    editCleanBtn.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    /**
     * 查找action
     */
    private void search() {
        String s = searchEdit.getText().toString();
        if (!DataUtil.isEmpty(s)) {
            String uuid = "";
            if (userData != null) {
                uuid = userData.getUuid();
            }
            SearchHistoryHelper.getsInstance().saveHistory(new SearchHistory(s, System.currentTimeMillis() / 1000, uuid));
            page = 1;
            mPresenter.requestSearchFromModel(s, page);
            initHistoryData();
        }
    }


    /**
     *  历史搜索
     */
    private void initHistoryData() {
        String uuid = "";
        if (userData != null) {
            uuid = userData.getUuid();
        }
        searchHistorys = SearchHistoryHelper.getsInstance().findAll(uuid);
        if (searchHistorys != null && searchHistorys.size() > 0) {
            searchHistoryTitle.setVisibility(View.VISIBLE);
            setFeedData(searchHistorys);
            searchHistoryTitle.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (searchHistorys.size() > 0) {
                        SearchHistoryHelper.getsInstance().delHistoryAll();
                        setFeedData(null);
                    }
                }
            });
        } else {
            searchHistoryTitle.setVisibility(View.GONE);
            feedLayout.setVisibility(View.GONE);
        }

    }


    /**
     *  设置搜索历史
     * @param tlist
     */
    private void setFeedData(List<SearchHistory> tlist) {
        tags.clear();
        if (tlist != null && tlist.size() > 0) {
            feedLayout.setVisibility(View.VISIBLE);
            searchHistoryTitle.setVisibility(View.VISIBLE);
            for (int i = 0; i < tlist.size(); i++) {
                tags.add(new AutoLineFeedView.AutoTextData(tlist.get(i).getName()));
            }
        } else {
            feedLayout.setVisibility(View.GONE);
            searchHistoryTitle.setVisibility(View.GONE);
        }
        feedLayout.setTags(tags, 10);
        feedLayout.setOnTagClickListener(new AutoLineFeedView.OnTagClickListener() {
            @Override
            public void onTagClick(View v, int position) {
                String s = tlist.get(position).getName();
                searchEdit.setText(s);
                searchEdit.setSelection(s.length());
                page = 1;
                mPresenter.requestSearchFromModel(s, page);
            }
        });


    }


    /**
     * 是否显示 搜索列表listView
     * @param isShowList
     */
    private void setlp(boolean isShowList) {
        if (isShowList) {
            listView.setVisibility(View.VISIBLE);
        } else {
            listView.setVisibility(View.GONE);
        }
    }


    private void initFeedView() {
        feedLayout = findViewById(R.id.historyLay);
        feedLayout.setOnTagClickListener(this);
    }


    @Override
    public void onTagClick(View v, int position) {

    }

    private void initSearchResult() {
        listView = findViewById(R.id.list);
        listView.setLayoutManager(new GridLayoutManager(this, 1));
        adapter = new BookrackSearchBookAdapter(this, searchList);
        listView.setAdapter(adapter);
        setlp(false);
    }

    private void initRefresh() {
        refresh = findViewById(R.id.refresh);
        refresh.setOnMultiPurposeListener(new SimpleMultiPurposeListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                page = 1;
                mPresenter.requestSearchFromModel(searchKey, page);
            }

            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page++;
                mPresenter.requestSearchFromModel(searchKey, page);
            }
        });
    }

    private void initEmpty() {
        empty = findViewById(R.id.empty);
        TextView emptyTv = findViewById(R.id.emptyTv);
        ImageView img = findViewById(R.id.emptyImg);
        img.setImageResource(R.drawable.error_search);
        emptyTv.setText(getString(R.string.search_empty_tv));
        findViewById(R.id.retryBtn).setVisibility(View.GONE);

    }

}
